import Vue from "vue";
import axios from "axios";
import { Message, Loading } from "element-ui";
import router from "../router";
// import VueCookies from 'vue-cookies'
// Vue.use(VueCookies)
// 环境的切换
// if (process.env.NODE_ENV == 'development') {
//     axios.defaults.baseURL = 'https://www.baidu.com';}
// else if (process.env.NODE_ENV == 'debug') {
//     axios.defaults.baseURL = 'https://www.ceshi.com';
// }
// else if (process.env.NODE_ENV == 'production') {
//     axios.defaults.baseURL = 'https://www.production.com';
// }
// 创建axios实例
var instance = axios.create({ timeout: 1000 * 12 });
// 设置post请求头
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

/**
 * 请求拦截
 */
instance.interceptors.request.use(
  config => {
    //在发送请求之前做某件事
    // if(config.method  === 'post'){
    //     config.data = qs.stringify(config.data);//POST传参序列化(添加请求拦截器)
    // }

    config.headers["gitssessionid"] =
      sessionStorage.getItem("gitssessionid") || ""; // 请求头带上token
    // if (config.url.indexOf("login") == -1) {
    //   Loading.service({
    //     lock: true,
    //     text: "Loading",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)"
    //   });
    // }
    return config;
  },
  error => {
    Message.error({ message: "请求超时!" });
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
instance.interceptors.response.use(
  response => {
    //对响应数据做些事
    // if (response.config.url.indexOf("login") == -1) {
    //   Loading.service().close();
    // }
    if (response.data.code === 0) {

    } else if (response.data.code === 11003) {
      Message.error({ message: "登录失效，请重新登录!" });
      router.push({
        path: "/login",
        querry: { redirect: router.currentRoute.fullPath } //从哪个页面跳转
      });
    } else {
      console.log(666);
      Message.error({ message: response.data.message });
    }
    return response;
  },
  error => {
    console.log(777);
    // Loading.service().close();
    console.log(error.response.data.message);
    Message.error({ message: error.response.data.message });
    return Promise.reject(error);
  }
);

export default instance;
